﻿using System;
using Sunny.UI;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ClassLibrary;
using ClassLibrary.Service;
using Forms.Properties;
using System.Reflection.Metadata;

namespace Forms
{
    public partial class Itembox : UIUserControl
    {
        //从外部传入的数据
        Item item = new Item();
        Label sumLabel = new Label();
        List<Good> goods = new List<Good>();
        //内部变量
        ItemService itemService = new ItemService();
        GoodService goodService = new GoodService();
        Good good, thisGood;
        User user;
        string goodID;//为购买的商品定义一个ID
        int count;//用于记录该商品的购买数量
        double sum;//用于记录选中的总金额
        UIButton CompleteButton = new UIButton();
        public Itembox(Item item, Label sumLabel, List<Good> goods)
        {
            InitializeComponent();
            this.item = item;
            this.sumLabel = sumLabel;
            this.goods = goods;
            ImageButton.Image = ImageService.BytesToImage(item.ItemPicture);
            goodID = Guid.NewGuid().ToString();
            good = new Good(goodID, item.ItemName, item.ItemPrice, 0, item.ItemID, "0", false);
            InitItembox();
        }
        public Itembox(User user, Item item)
        {
            SetStyle(
                ControlStyles.UserPaint//使用自定义的绘制方式
                | ControlStyles.ResizeRedraw//当控件大小发生变化时就重新绘制
                | ControlStyles.DoubleBuffer// 双缓冲
                | ControlStyles.SupportsTransparentBackColor//则控件接受 alpha 组件数小于 255 个的 BackColor 来模拟透明度
                | ControlStyles.AllPaintingInWmPaint//禁止擦除背景.则控件忽略窗口消息 WM_ERASEBKGND 以减少闪烁
                | ControlStyles.EnableNotifyMessage// 
                                                   // Enable the OnNotifyMessage event so we get a chance to filter out 
                                                   // Windows messages before they get to the form's WndProc
                | ControlStyles.OptimizedDoubleBuffer//则控件将首先绘制到缓冲区而不是直接绘制到屏幕，这可以减少闪烁
                , true);
            InitializeComponent();
            this.user = user;
            this.item = item;
            uiLabel3.Text = "";
            uiLabel2.Text = "剩余数量";
            DeleteBtn.Visible = false;
            GoodCountLabel.Visible = false;
            AddBtn.Visible = false;
            ImageButton.Image = ImageService.BytesToImage(item.ItemPicture);
            ItemNameLabel.Text = item.ItemName;
            PriceLabel.Text = item.ItemPrice.ToString("0.00") + " ¥";
            MarketLabel.Text = Convert.ToString(item.ItemCount);
            Button lookButton = new Button();
            // 相对于应用程序启动路径的相对路径
            string relativePath = @"..\..\..\picture\ItemDetail.png";
            string FilePath = " ";
            // 获取应用程序的启动路径
            string appStartupPath = AppDomain.CurrentDomain.BaseDirectory;

            // 合并启动路径和相对路径
            FilePath = Path.GetFullPath(Path.Combine(appStartupPath, relativePath));
            lookButton.BackgroundImage = Image.FromFile(FilePath);
            lookButton.FlatAppearance.MouseDownBackColor = Color.Lime;
            lookButton.FlatAppearance.MouseOverBackColor = Color.Transparent;
            lookButton.FlatStyle = FlatStyle.Flat;
            lookButton.ForeColor = Color.Transparent;
            lookButton.Size = new Size(32, 30);
            lookButton.UseVisualStyleBackColor = true;
            lookButton.FlatAppearance.BorderSize = 0;
            lookButton.Click += LookButton_Click;
            lookButton.Location = new Point(350, 120);
            lookButton.BackgroundImageLayout = ImageLayout.Zoom;
            //lookButton.Text = "查看详细";
            //lookButton.Size = new Size(100, 35);
            Controls.Add(lookButton);
        }
        public Itembox(User user, Good good)
        {
            SetStyle(
                ControlStyles.UserPaint//使用自定义的绘制方式
                | ControlStyles.ResizeRedraw//当控件大小发生变化时就重新绘制
                | ControlStyles.DoubleBuffer// 双缓冲
                | ControlStyles.SupportsTransparentBackColor//则控件接受 alpha 组件数小于 255 个的 BackColor 来模拟透明度
                | ControlStyles.AllPaintingInWmPaint//禁止擦除背景.则控件忽略窗口消息 WM_ERASEBKGND 以减少闪烁
                | ControlStyles.EnableNotifyMessage// 
                                                   // Enable the OnNotifyMessage event so we get a chance to filter out 
                                                   // Windows messages before they get to the form's WndProc
                | ControlStyles.OptimizedDoubleBuffer//则控件将首先绘制到缓冲区而不是直接绘制到屏幕，这可以减少闪烁
                , true);
            InitializeComponent();
            this.user = user;
            this.thisGood = good;
            uiLabel3.Visible = false;
            uiLabel2.Text = "出售数量";
            DeleteBtn.Visible = false;
            GoodCountLabel.Visible = false;
            AddBtn.Visible = false;
            ImageButton.Image = ImageService.BytesToImage(itemService.GetItemByItemID(good.ItemID)[0].ItemPicture);
            ItemNameLabel.Text = good.GoodName;
            PriceLabel.Text = good.GoodPrice.ToString("0.00") + " ¥";
            MarketLabel.Text = Convert.ToString(good.GoodCount);
            ImageButton.Click += ImageButton_Click;
            CompleteButton.Click += CompleteButton_Click;
            CompleteButton.Location = new Point(310, 120);
            CompleteButton.Size = new Size(100, 35);
            Controls.Add(CompleteButton);
            if (thisGood.GoodStatus == false)
            {
                CompleteButton.Enabled = true;
                CompleteButton.Text = "确认完成";
            }
            else
            {
                CompleteButton.Enabled = false;
                CompleteButton.Text = "已完成";
            }
        }
        public delegate void FlashParentFormType();
        public event FlashParentFormType FlashParentForm;
        private void LookButton_Click(object? sender, EventArgs e)
        {
            AddItem lookItem = new AddItem(user, item);
            lookItem.ShowDialog();
            FlashParentForm();
        }
        public bool ShowAskDialog(string msg, bool showMask = true)
        {
            return UIMessageDialog.ShowMessageDialog(msg, UILocalize.AskTitle, true, UIStyle.Blue, showMask);
        }
        public void ShowSuccessTip(string text, int delay = 1000, bool floating = true)
            => UIMessageTip.ShowOk(text, delay, floating);
        public void ShowErrorTip(string text, int delay = 1000, bool floating = true)
            => UIMessageTip.ShowError(text, delay, floating);
        private void CompleteButton_Click(object? sender, EventArgs args)
        {
            if (ShowAskDialog("确认提示框"))
            {
                thisGood.GoodStatus = true;
                goodService.ModifyGood(thisGood);
                CompleteButton.Enabled = false;
                ShowSuccessTip("商品确认完成");
            }
            else
            {
                ShowErrorTip("商品取消确认");
            }
        }
        public void ImageButton_Click(object? sender, EventArgs args)
        {
            GoodDetails goodDetails = new GoodDetails(thisGood);
            goodDetails.FlashParentForm += GoodDetails_FlashParentForm;
            goodDetails.ShowDialog();
        }
        private void GoodDetails_FlashParentForm()
        {
            FlashParentForm();
        }

        private void InitItembox()
        {
            ItemNameLabel.Text = item.ItemName;
            PriceLabel.Text = item.ItemPrice.ToString("0.00") + " ¥";
            List<Market> markets = itemService.GetMarketByItem(item);//根据商品返回所属超市

            // List<User> users = itemService.GetUserByItem(item);//根据商品返回所属超市的所属用户
            MarketLabel.Text = markets[0].MarketName;
            CountLabel.Text = item.ItemCount.ToString();
            GoodCountLabel.Text = "0";
            count = 0;
        }

        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            if (count > 0)
            {
                //购买数目和总金额的更新
                count--;//购买数目减一
                GoodCountLabel.Text = count.ToString();//更新购买数量
                sum = sumLabel.Text.ToDouble();
                sum -= item.ItemPrice;
                sumLabel.Text = sum.ToString("0.00");//更新总金额
                //good购买数目的更新
                good.GoodCount = count;
                //对List<Good>的更新
                if (count == 0)//如果购买数目变为0，则直接删除
                {
                    Good oldgood = goods.Find(g => g.GoodID == goodID);
                    goods.Remove(oldgood);
                }
                else //否则先删除oldgood，再添加
                {
                    Good oldgood = goods.Find(g => g.GoodID == goodID);
                    goods.Remove(oldgood);
                    goods.Add(good);
                }
            }
            else
            {
                MessageBox.Show("商品数目不可小于0");
            }
        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            if (count < item.ItemCount) //如果商品剩余数量大于购买数量
            {
                //购买数目和总金额的更新
                count++;//购买数目加一
                GoodCountLabel.Text = count.ToString();//更新购买数量
                sum = sumLabel.Text.ToDouble();
                sum += item.ItemPrice;
                sumLabel.Text = sum.ToString("0.00");//更新总金额
                //good购买数目的更新
                good.GoodCount = count;
                //对List<Good>的更新
                if (count == 1)//如果是首次添加good，则直接添加
                {
                    goods.Add(good);
                }
                else //否则先删除oldgood，再添加
                {
                    Good oldgood = goods.Find(g => g.GoodID == goodID);
                    goods.Remove(oldgood);
                    goods.Add(good);
                }
            }
            else
            {
                MessageBox.Show("商品剩余数量不足");
            }
        }

        private void ImageButton_Click_1(object sender, EventArgs e)
        {

        }
    }
}
